package it.blog.controller;

import it.blog.stub.AuthBlogPortal;
import it.blog.stub.AuthBlogPortalService;
import it.blog.stub.Blog;
import it.blog.stub.User;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import com.oreilly.servlet.MultipartRequest;




public class UploadImage extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	 
	 HttpSession session =  request.getSession();
	 AuthBlogPortalService us= new AuthBlogPortalService();
	 W3CEndpointReference ref=(W3CEndpointReference)session.getAttribute("ref");
	 AuthBlogPortal userAuthenticate=us.getPort(ref, AuthBlogPortal.class);
	 User user =(User) session.getAttribute("user");
	 Blog blog = (Blog) session.getAttribute("blog");
	 
	 MultipartRequest multi = new MultipartRequest(request,".");
	 File f = multi.getFile("file");
	 String ext=this.getExtension(f);
	 String fileName;
	 String namePath=multi.getParameter("path");
	 String secondPath="";
	 String imgURL="";
	 
	 if(namePath.equals("blogs")){
		 imgURL=blog.getImgURL();
		 fileName=blog.getBlogID()+"."+ext;
	 }	 
	 else{
		 imgURL=user.getImgURL();
		 fileName=user.getUserID()+"."+ext;
	 }
	 secondPath=namePath+"/"+imgURL;
	 
	 if (f!=null)
	 {
	 File fOUT = new File("./webapps"+request.getContextPath()+"/"+secondPath);  
	 if(imgURL!=null && !imgURL.equals("") && fOUT.exists()){
		 fOUT.delete();
	 }
	 
		 
	 fOUT = new File("./webapps"+request.getContextPath()+"/"+namePath+"/",fileName);
	 FileInputStream fIS = new FileInputStream(f);
	 FileOutputStream fOS = new FileOutputStream(fOUT);
	  while (fIS.available()>0)
	   fOS.write(fIS.read());
	 fIS.close();
	 fOS.close();
	}
	 
	 if(namePath.equals("users")){
		 user.setImgURL(fileName);
		 if(userAuthenticate.updateUser(user)){
			session.setAttribute("user",user);
		 }else{
			session.setAttribute("mess","aggiornamento utente fallito");
		 }
	 }
	 else{

		 blog.setImgURL(fileName);
		 if(userAuthenticate.updateBlog(blog))
			session.setAttribute("blog", blog);
		 else	 
			session.setAttribute("mess","aggiornamento blog fallito");
	
		 
	 }
	 response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/PortalServlet"));
	}
	
	private String getExtension(File f) {
	        String ext = null;
	        String s = f.getName();
	        int i = s.lastIndexOf('.');

	        if (i > 0 &&  i < s.length() - 1) {
	            ext = s.substring(i+1).toLowerCase();
	        }
	        return ext;
	    }
}